﻿using CPFrameWork.Global;
using System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using CPFrameWork.Utility.DbOper;
using BusinessManage.Common;
using static CPFrameWork.UIInterface.Grid.GridEngineController;
using CPFrameWork.UIInterface.Grid;
using System.Data;
using System.Text;
using NLog;
using System.Collections.Generic;

namespace BusinessManage
{
    /**
     * Auhtor:WANGYY
     * DESC:分厅
     * **/
    public class HatchRoomController : CPWebApiBaseController
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        [HttpPost]
        public string GetSourceInfo([FromBody] FieldSource fieldSource)
        {
            HatchRoom hatchRoom = new HatchRoom();
            return  JsonConvert.SerializeObject(hatchRoom.ReadColumnListData(fieldSource));
        }

        [HttpGet]
        public string GetInfo()
        {
            return "OK";

        }
        /// <summary>
        ///订单分厅保存
        /// </summary>
        /// <param name="reportData"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity SaveGridData([FromBody] ReportData reportData)
        {
         
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                int CurUserId = Convert.ToInt32( reportData.CurUserId);
                string CurUserIden = reportData.CurUserIden;

                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                HatchRoom hatchRoom = new HatchRoom();
                foreach (Items item in reportData.Items)
                {
                    re = hatchRoom.SaveYW_GivetohallInfo(item,Convert.ToInt32( reportData.CurUserId),reportData.GridCode);
                    //订单操作日志
                    OrderOperateLog orderOperateLog = new OrderOperateLog()
                    {
                        DbIns = "CPYKWL",
                        LinkType = "20",
                        LinkName = "订单分厅保存",
                        orderid = item.OrderId,
                        OperateName= "订单分厅保存"
                    };
                    OrderLog.OrderOperateLog(orderOperateLog);
                }
                return re;
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("【订单分厅】保存功能,发生异常，异常信息为{0}", ex.Message));
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
          

        }


        /// <summary>
        /// 分厅调整，修改保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity SaveUpdateData([FromBody] UpdateDataInput input)
        {
            base.SetHeader();

            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            if (this.CheckUserIden(input.CurUserId, input.CurUserIden) == false)
            {
                re.Result = false;
                re.ErrorMsg = "登陆超时，请退出重新登陆！";
                return re;
            }
            CPGrid grid = CPGridEngine.Instance(input.CurUserId).GetGrid(input.GridCode, false, false);
            DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());

            if (!this.DeleteDataForFormId(dbHelper, input.Items).Result) return re;
            try
            {
                #region save数据
                HatchRoom hatchRoom = new HatchRoom();
                foreach (Items item in input.ADDItems)
                {
                    re = hatchRoom.CopyYW_GivetohallInfo(item, Convert.ToInt32(input.CurUserId), input.GridCode);
                    //订单操作日志
                    OrderOperateLog orderOperateLog = new OrderOperateLog()
                    {
                        DbIns = "CPYKWL",
                        LinkType = "20",
                        LinkName = "分厅修改",
                        orderid = item.OrderId,
                        OperateName= "分厅调整，修改保存"
                    };
                    OrderLog.OrderOperateLog(orderOperateLog);
                }
                return re;
                #endregion
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("【分厅调整】保存,发生异常，异常信息为{0}", ex.Message));
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }

            re.Result = true;
            return re;
        }

        [HttpPost]
        public CPWebApiBaseReturnEntity DeleteGridData([FromBody] UpdateDataInput input)
        {
            base.SetHeader();
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                if (this.CheckUserIden(input.CurUserId, input.CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                CPGrid grid = CPGridEngine.Instance(input.CurUserId).GetGrid(input.GridCode, false, false);
                DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());
                if (!this.DeleteDataForFormId(dbHelper, input.Items).Result) return re;

                re.Result = true;
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("【分厅调整】删除,发生异常，异常信息为{0}", ex.Message));
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
            return re;
        }


        #region 私有方法
        /// <summary>
        /// 根据订单删除排线相关订单
        /// </summary>
        /// <param name="dbHelper"></param>
        /// <param name="updateItemList"></param>
        /// <returns></returns>
        private CPWebApiBaseReturnEntity DeleteDataForFormId(DbHelper dbHelper,List<UpdateDataInputItem>  updateItemList) {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {

                #region update数据
                StringBuilder sb = new StringBuilder();
                //调整【任务分配车辆表】
                string delSql = " delete from dbo.YW_TaskCarRelation where OrderId in (select OrderId  from dbo.YW_TaskOrderRelation where  GivetohallId  in (";
                for (int i = 0; i < updateItemList.Count; i++)
                {
                    UpdateDataInputItem updateItem = updateItemList[i];
                    delSql += updateItem.DataPK + ",";
                }
                delSql = delSql.TrimEnd(',') + "));";
                //调整【配送任务与订单关系表】
                delSql += "delete  from dbo.YW_TaskOrderRelation  where GivetohallId in (";
                for (int i = 0; i < updateItemList.Count; i++)
                {
                    UpdateDataInputItem updateItem = updateItemList[i];
                    delSql += updateItem.DataPK + ",";
                }
                delSql = delSql.TrimEnd(',') + ");";
             
                if (sb.Length > 0)
                    sb.Append(";");
                sb.Append(delSql);

                if (sb.Length > 0)
                {
                    System.Diagnostics.Debug.WriteLine(sb.ToString());
                    dbHelper.ExecuteNonQuery(sb.ToString());
                }

                #endregion
                re.Result= true;
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("【分厅调整】修改,发生异常，异常信息为{0}", ex.Message));
                re.Result= false;
                re.ErrorMsg = ex.Message;
            }
            return re;
        }
    
        private bool CheckUserIden(int UserId, String SessionKey)
        {
            try
            {
                new Guid(SessionKey);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
            DbHelper _helper = new DbHelper("CPOrganIns", CPAppContext.CurDbType());
            string strSql = " SELECT UserId FROM CP_UserIdentity WHERE UserKey='" + SessionKey + "'";
            object userIdDb = _helper.ExecuteScalar(strSql);
            if (Convert.IsDBNull(userIdDb) || userIdDb == null)
                return false;
            else
            {
                if (int.Parse(userIdDb.ToString()).Equals(UserId))
                    return true;
                else
                    return false;
            }
        }
        #endregion



    }

}
